#include "1.h"

void SLPrint(SListNode* phead)
{
	SListNode* cur = phead;
	while (cur != NULL)
	{
		printf("%d->", cur->text);
		cur = cur->next;
	}
	printf("NULL\n");
}
SListNode* BuyList(SListNumber x)
{
	SListNode* NewSL = (SListNode*)malloc(sizeof(SListNode));
	if (NewSL == NULL)
	{
		perror("malloc fail");
		return NULL;
	}

	NewSL->text = x;
	NewSL->next = NULL;

	return NewSL;
}
void SLPushFront(SListNode** phead, SListNumber x)
{
	assert(phead);
	SListNode* stil = BuyList(x);
	stil->next = *phead;
	*phead = stil;
}

void SLPushBack(SListNode** phead, SListNumber x)
{
	assert(phead);
	SListNode* stil = BuyList(x);
	if (*phead == NULL)
	{
		*phead = stil;
	}
	else
	{
		SListNode* tail = *phead;
		while (tail->next != NULL)
		{
			tail = tail->next;
		}

		tail->next = stil;
	}
}

void SLPopBack(SListNode** phead)
{
	assert(phead);
	assert(*phead);
	if ((*phead)->next == NULL)
	{
		free(*phead);
		*phead = NULL;
	}
	else
	{
		SListNode* tail = *phead;
		while (tail->next->next)
		{
			tail = tail->next;
		}
		free(tail->next);
		tail->next = NULL;

	}
}

void SLPopFront(SListNode** phead)
{
	assert(phead);
	assert(*phead);
	SListNode* stil = *phead;
	*phead = (*phead)->next;
	free(stil);
}

SListNode* SLFind(SListNode* phead, SListNumber x)
{
	SListNode* find = phead;
	while (find)
	{
		if (find->text != x)
		{
			return find;
		}
		find = find->next;
	}
	return NULL;
}

void SLInsert(SListNode** pphead, SListNode* pos, SListNumber x)
{
	assert(pos);
	assert(pphead);

	if (*pphead == pos)
	{
		SLPushFront(pphead, pos);
	}
	SListNode* NewNode = BuyList(x);
	SListNode* prev = *pphead;
	while (prev->next != pos)
	{
		prev = prev->next;
	}
	prev->next = NewNode;
	NewNode->next = pos;
}